<template>
  <div id="three" style="border: 1px solid black; width: 1200px; height: 800px">src/pages/THREE /basic</div>
</template>

<script setup lang="ts">
import * as THREE from 'three';
import { Color as ThreeColor, AxesHelper as TAxesHelper } from 'three';

import { onMounted } from 'vue';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

onMounted(() => {
  // Renderer初始化
  const renderer = new THREE.WebGLRenderer();
  renderer.setClearColor(0x444444, 1); //设置背景颜色

  renderer.setSize(1200, 800);
  document.getElementById('three').appendChild(renderer.domElement);

  // 相机初始化
  const camera = new THREE.PerspectiveCamera(45, 1200 / 800, 20, 2000);
  camera.position.set(800, 800, 800);
  camera.lookAt(0, 0, 0);

  // 创建场景
  const scene = new THREE.Scene();

  // 添加物体
  const geometry2 = new THREE.BoxGeometry(200, 200, 200);
  const mesh = new THREE.Mesh(
    geometry2,
    // new THREE.MeshBasicMaterial({ color: 0x008800, transparent: true, opacity: 0.5 }),
    new THREE.MeshLambertMaterial({ color: 0x008800, transparent: true, opacity: 0.5 }), //受光照影响
  );
  scene.add(mesh);

  // 添加坐标轴辅助线
  const axesHelper = new TAxesHelper(1500);
  axesHelper.setColors(ThreeColor.NAMES.red, ThreeColor.NAMES.green, ThreeColor.NAMES.blue);
  scene.add(axesHelper);

  // 设置相机控件轨道控制器OrbitControls
  const controls = new OrbitControls(camera, renderer.domElement);
  // 如果OrbitControls改变了相机参数，重新调用渲染器渲染三维场景
  controls.addEventListener('change', () => {
    renderer.render(scene, camera);
  });

  //   添加光源
  const light = new THREE.PointLight(0xffffff, 1.0);
  light.intensity = 300.0; //光照强度
  light.decay = 0.0; //设置光源不随距离衰减
  light.position.set(330, 330, 330);
  scene.add(light);

  //环境光:没有特定方向，整体改变场景的光照明暗
  const ambient = new THREE.AmbientLight(0xffffff, 0.4);
  scene.add(ambient);

  // 渲染器渲染场景 一定要放在最后
  renderer.render(scene, camera);

  // 渲染函数
  function render() {
    renderer.render(scene, camera); //执行渲染操作
    mesh.rotateY(0.01); //每次绕y轴旋转0.01弧度
    requestAnimationFrame(render); //请求再次执行渲染函数render，渲染下一帧
  }
  render();
});
</script>

<style scoped lang="less"></style>
